<template>
    <div class="ml-16px mr-16px pt-36px pl-26px pr-26px content-container">
        <div class="h-500px" v-loading="state.isLoading" v-if="state.isLoading"></div>
        <template v-else>
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="124px">
                <el-form-item label="文章标题" prop="name">
                    <div class="w-400px">
                        <el-input ref="nameRef" v-model="ruleForm.name" placeholder="请输入文章标题" />
                    </div>
                </el-form-item>
                <el-form-item label="所在地区" prop="area">
                    <ProvinceCitySelector ref="provinceCitySelector" v-model:province="ruleForm.province"
                        v-model:city="ruleForm.city" />
                </el-form-item>
                <el-form-item label="详细介绍" prop="content">
                    <div class="w-90%">
                        <vue-ueditor-wrap v-model="ruleForm.content" editor-id="articleEditor" :config="editorConfig"
                            :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" />
                    </div>
                    <div class="text-12px text-#999">为了保证关键词名效果，详细介绍请不低于200个汉字，在详细内容中不要填写任何联系方式(如联系人、联系电话、传真、手机、邮箱、网站等。
                    </div>
                </el-form-item>
                <el-form-item label="文章来源" prop="source">
                    <div class="w-400px">
                        <el-input ref="nameSource" v-model="ruleForm.source" placeholder="请输入文章来源" />
                    </div>
                </el-form-item>

                <el-form-item label="文章主关键词" prop="mainKeyword">
                    <div class="w-150px">
                        <el-input ref="nameRef" v-model="ruleForm.mainKeyword" :disabled="true" />
                    </div>
                </el-form-item>
                <el-form-item label="替换文章关键词" prop="keywords" v-if="!ruleForm.mainPid && ruleForm.keywords.length > 0">
                    <div class="flex flex-wrap">
                        <div class="w-150px mr-12px mb-5px" v-for="(item, index) in ruleForm.keywords" :key="index">
                            <el-input :disabled="true" v-model="ruleForm.keywords[index]" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="pb-40px">
                        <el-button type="primary" @click="handleNext(ruleFormRef)">确认修改</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </template>
    </div>
</template>

<script setup lang="ts">
import { CircleCloseFilled,SuccessFilled } from '@element-plus/icons-vue'
import { checkArticleContentApi,getArticleDetailApi,editArticleApi } from '@/api/b2b'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { findMatchingElements, debounce } from '@/utils/index'
import type { FormInstance } from 'element-plus'
import { normalStr, violationStr } from '@/utils/checkStr'
import ProvinceCitySelector from '@/components/ProvinceCitySelector/index.vue'

const route = useRoute()
const router = useRouter()

const state = reactive({
    step: 0,
    isLoading: true,
    isError: false,
})

const ruleFormRef = ref()
const nameRef = ref()

const ruleForm = reactive({
    name: '',
    province: '',
    city: '',
    area: '',
    content: '',
    mainKeyword: '',
    keywords: <string[]>[],
    source: '',
    mainPid: ''
})

const rules = reactive({
    name: [
        { min: 3, max: 35, required: true, message: '请输入文章标题', trigger: 'blur', validator: checkName }
    ],
    content: [
        { required: true, validator: checkContent }
    ],
    mainKeyword: [
        { required: true }
    ],
    keywords: [
        { required: true }
    ]
})

const provinceCitySelector = ref<InstanceType<typeof ProvinceCitySelector> & ProvinceCitySelectorInstance | null>(null)

const editorConfig = {
    // 后端服务地址，后端处理参考
    // https://open-doc.modstart.com/ueditor-plus/backend.html
    serverUrl: import.meta.env.VITE_APP_EDITOR_URL,
    UEDITOR_HOME_URL: '/static/UEditorPlus/',
    UEDITOR_CORS_URL: '/static/UEditorPlus/',
    /* 上传图片配置项 */
    imageActionName: 'uploadFile' /* 执行上传图片的action名称 */,
    imageFieldName: 'file' /* 提交的图片表单名称 */,
    imageMaxSize: 2048000 /* 上传大小限制，单位B */,
    imageAllowFiles: ['.png', '.jpg', '.jpeg', '.gif', '.bmp'] /* 上传图片格式显示 */,
    imageCompressEnable: true /* 是否压缩图片,默认是true */,
    imageCompressBorder: 1600 /* 图片压缩最长边限制 */,
    imageInsertAlign: 'none' /* 插入的图片浮动方式 */,
    imageUrlPrefix: '' /* 图片访问路径前缀 */,
    imagePathFormat: '' /* 上传保存路径,可以自定义保存路径和文件名格式 */,
    autoHeightEnabled:false,

    serverHeaders: {
        'Authorization': sessionStorage.getItem('X-token')
    },
}

function checkName(rule: any, value: any, callback: any) {
    if (value === '') {
        callback(new Error('请输入文章标题'))
    } else {
        const arr = findMatchingElements(value, normalStr)
        if (arr.length) {
            confirmMessageBox(CircleCloseFilled, '文章标题里不能包含 ' + arr[0] + ' 请修改', '','',() => {
                nameRef.value.focus()
            })
            callback(new Error()) // 必须调用 callback 来通知校验失败
        } else {
            callback() // 校验通过
        }
    }
}

function checkContent(rule: any, value: any, callback: any) {
    console.log(value)
    if (value === '') {
        callback(new Error('请输入文章详细内容'))
    } else {
        value = value.replace(/<[^>]+>/g, '')
        if(value.length < 200){
            confirmMessageBox(CircleCloseFilled, '文章详细内容不能少于 200 个字符', '','')
            callback(new Error('文章详细内容不能少于 200 个字符'))
        }
        const arr = findMatchingElements(value, violationStr)
        if (arr.length) {
            confirmMessageBox(CircleCloseFilled, '您发布的信息中不能包含 ' + arr[0] + ' 请检查修改后提交')
            callback(new Error())
        } else {
            callback() // 校验通过
        }
    }
}

const debouncedCheckContent = debounce(async (newContent: string) => {
    if (!state.isError) {
        try{
            const res:ResType = await checkArticleContentApi({ content: newContent })
            if(res.code === 200){
                return true
            }
        }catch(error:any){
            confirmMessageBox(CircleCloseFilled, error.response.data.message, '确定','',() => {

            })
            return false
        }
    }
}, 300);

// watch(
//     () => ruleForm.content,
//     (newContent) => {
//         if(newContent){
//             debouncedCheckContent(newContent)
//         }
//     }
// );

async function handleNext(formEl: FormInstance | undefined) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try{
                const id = Number(route.params.id)
                const res:ResType = await editArticleApi({
                    ID: id,
                    Title: ruleForm.name,
                    Province: ruleForm.province,
                    City: ruleForm.city,
                    Detail: ruleForm.content,
                    Reprint: ruleForm.source 
                })
                if(res.code === 200){
                    confirmMessageBox(SuccessFilled, res.message,'','',() => {
                        router.push('/b2b/article/list')
                    })
                }
            }catch(error:any){
                confirmMessageBox(CircleCloseFilled, error.response.data.message, '','',() => {})
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

async function getArticleDetail() {
    const id = Number(route.params.id)
    const res = await getArticleDetailApi({ id: id })
    console.log(res)
    if (res.code === 200) {
        state.isLoading = false
        ruleForm.name = res.data.Title
        ruleForm.province = res.data.Province
        ruleForm.city = res.data.City
        ruleForm.content = res.data.Detail
        ruleForm.source = res.data.Reprint
        ruleForm.mainPid = res.data.PID
        ruleForm.mainKeyword = res.data.Keyword
        
        if(res.data.LKeyword){
            ruleForm.keywords = res.data.LKeyword.split('/')
        }

        nextTick(() => {
            if (provinceCitySelector.value) {
                const selector = provinceCitySelector.value
                selector.selectedProvince.name = res.data.Province
                selector.selectedCity = res.data.City
            }
        })
    }
}

onMounted(() => {
    getArticleDetail()
})
</script>

<style lang="scss" scoped></style>